package messangerServer;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import messangerTypes.MessageBase;

public class ServerUnicastSendWorker extends Thread
{
	private ObjectOutputStream out;
	private ConcurrentLinkedQueue<MessageBase> writeQueue;
	private Semaphore sem;
	private ServerBackend parent;
	private int port;
	public boolean quit = false;
	
	public ServerUnicastSendWorker (ServerBackend parent, int port, OutputStream out) throws IOException
	{
		writeQueue = new ConcurrentLinkedQueue<MessageBase>();
		sem = new Semaphore(0);
		this.out = new ObjectOutputStream(out);
	}

	public void write (MessageBase mb)
	{
		if(writeQueue.add(mb))
		{
			sem.release();
		}
		else
		{
			//i dont know add failed. may be the next one wont?
		}
	}
	
	public void run()
	{
		try
		{
						
			while(!quit)
			{
				//ensures there is to deadlock
				if(sem.tryAcquire(250, TimeUnit.MILLISECONDS))
				{
					MessageBase mb = writeQueue.poll();
					
					if(mb != null)
					{
						out.writeObject(mb);
						System.out.println("ServerUnicastSendWorker: " + mb.toString());	
						mb = null;
					}
					else
					{
						//queue was empty !?
					}
				}
				else
				{
					
				}
				
			}
					
		} 
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			parent.clientDisconnect(port);
			try
			{
				out.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	}
}
